package com.exampletest.service.impl;

import com.exampletest.mapper.UserMapper;
import com.exampletest.model.User;
import com.exampletest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static final String USER_CACHE = "users";

    @Autowired
    private UserMapper userMapper;

    @Override
    @CacheEvict(value = USER_CACHE, allEntries = true)
    public boolean register(User user) {
        if (userMapper.findByUsername(user.getUsername()) != null) {
            return false;
        }
        // 设置默认值
        if (user.getIsSuperAdmin() == null) {
            user.setIsSuperAdmin(false);
        }
        if (user.getStatus() == null) {
            user.setStatus(1); // 默认激活状态
        }
        if (user.getCreateTime() == null) {
            user.setCreateTime(new Date());
        }
        return userMapper.insertUser(user) > 0;
    }

    @Override
    @Cacheable(value = USER_CACHE, key = "#username", unless = "#result == null")
    public User login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    @Override
    @Cacheable(value = USER_CACHE, key = "'all_users'")
    public List<User> getAllUsers() {
        return userMapper.findAllUsers();
    }

    @Override
    @Cacheable(value = USER_CACHE, key = "#id")
    public User getUserById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    @CacheEvict(value = USER_CACHE, key = "#user.id")
    public boolean updateUser(User user) {
        return userMapper.updateUser(user) > 0;
    }

    @Override
    @CacheEvict(value = USER_CACHE, key = "#id")
    public boolean deleteUser(Integer id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    @CacheEvict(value = USER_CACHE, key = "#id")
    public boolean changeUserStatus(Integer id, Integer status) {
        return userMapper.updateStatus(id, status) > 0;
    }

    @Override
    public List<User> searchUsers(String keyword) {
        return userMapper.searchUsers(keyword);
    }
}